import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver } from '@angular/core';
import { NgModel, NgForm } from '@angular/forms';
import { environment } from '../../../../environments/environment';
import { AppPaginationComponent, PaginationModel } from "../../../widgets/pagination/pagination.component";
import { OnetomanyCheckService } from './check.service';
import * as moment from 'moment';
import * as _ from 'lodash';
import { DataService } from '../../../services/data.service';
import { OnetomanyCheckModalComponent } from '../modal/check/check.component';
import { Util } from 'app/common/util';
@Component({
  selector: 'onetomany-check',
  templateUrl: './check.component.html',
  styleUrls: ['./check.component.scss'],
  providers: [OnetomanyCheckService]
})
export class OnetomanyCheckComponent implements OnInit {
  // 引用模板里面定义的fundInfoHistory容器标签
  @ViewChild("checkModal", { read: ViewContainerRef })
  checkModal: ViewContainerRef;
  // 变更注册组件变量
  checkModalComponent: ComponentRef<OnetomanyCheckModalComponent>;
  //到期日
  public dEnd: any;
  // 一对多基础信息
  public otmAddOrEditBody: any = {};
  // lodash
  public _: any = _;
  // 获取权限按钮
  public menuResourceSet: any;

  public menuData: any;
  //  托管人数据
  // public bankDictionaryList = [];
  // 列表是否全选
  public isCheckedAll = false;
  // 一对多审核列表数据
  public otmCheckList: any;
  // 一对多审核列表
  public otmCheckBody: any = {
    pageIndex: 1,
    pageSize: 10,
    sFundCode: "",
    sFullName: "",
    sType: "",
    sStatus: "",
    sFundType: "2"
  };
  // 一对多审核列表分页配置
  public otmCheckListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  constructor(
    public otmCheckService: OnetomanyCheckService,
    private resolver: ComponentFactoryResolver,
    public dataservice: DataService

  ) { }
  ngOnInit() {
    // 获取审核列表
    this.getCheckList();
    // 权限处理
    this.dataservice.initTree.subscribe((data) => {
      let SessionMenuData = sessionStorage.getItem('menu');
      this.menuData = JSON.parse(SessionMenuData)
      this.menuResourceSet = [];
      _.forEach(this.menuData, (item, index) => {
        if (item.sName == '一对多专户') {
          _.forEach(item.children, (it, idx) => {
            if (it.sName == '修改审核') {
              this.menuResourceSet = it.resourceSet
            }

          })
        }
      })
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '一对多专户') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '修改审核') {
            this.menuResourceSet = it.resourceSet
          }

        })
      }
    })
    // 获取托管人数据
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
  }
  // 一对多审核列表
  getCheckList(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.otmCheckBody.sFullName = _.trim(this.otmCheckBody.sFullName);
    this.otmCheckBody.sFundCode = _.trim(this.otmCheckBody.sFundCode);
    this.otmCheckBody.pageIndex = pageNum ? pageNum : this.otmCheckListPageInfo.currentPageNum;
    this.otmCheckBody.pageSize = pageSize ? pageSize : this.otmCheckListPageInfo.pageSize;
    this.otmCheckService.getCheckMainList(this.otmCheckBody).subscribe(data => {
      if (data) {
        that.otmCheckList = data.list;
        that.otmCheckListPageInfo.currentPageNum = data.pageNum;
        that.otmCheckListPageInfo.totalPages = data.pages;
        that.otmCheckListPageInfo.total = data.total;
        that.otmCheckListPageInfo.startRow = data.startRow;
        that.otmCheckListPageInfo.endRow = data.endRow;
      }
      // // 给表格列支持列拖动效果
      // setTimeout(() => {
      //   Util.colResizable("#fixed-table");
      // }, 100);

      // 给表格列支持列拖动和固定表头效果
      Util.colResizable("#checkList");
    })
  }
  // 一对多审核列表切换页
  otmCheckPagesizeChange(pageSize: number) {
    if (pageSize !== this.otmCheckListPageInfo.pageSize) {
      this.otmCheckListPageInfo.pageSize = pageSize;
      this.getCheckList();
    }
  }
  // 一对多审核列表分页
  otmCheckPageNavigation(currentPageNum: number) {
    this.otmCheckListPageInfo.currentPageNum = currentPageNum;
    this.getCheckList(this.otmCheckListPageInfo.currentPageNum, this.otmCheckListPageInfo.pageSize);
  }
  // 全选或全不选
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.otmCheckList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.otmCheckList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.otmCheckList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.otmCheckList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 审核通过
  checkPass() {
    let that = this;
    let checkProduct = [];
    let nFundNoList = [];
    let nAuditNoList = [];
    let sStatusList = [];
    let sTypeList = [];
    _.forEach(this.otmCheckList, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    // 无勾选
    if (checkProduct.length < 1) {
      window['swal']("注意", "请选择修改记录后再进行审核操作!", "warning")
    }
    // 勾选一个
    if (checkProduct.length == 1) {
      //根据nExaminNo查询审核明细，判断修改项是否为到期日
      this.otmCheckService.getCheckDetailList({
        pageIndex: "1",
        pageSize: "10",
        sFundType: "2",
        nExaminNo: checkProduct[0].nExaminNo
      }).subscribe(body => {
        if (body) {
          //判断修改项是否为到期日,并且修改后为空，是则打开添加到期日modal
          if (checkProduct[0].sType == '2' && body.list[0].sModifyItem == '到期日' && !body.list[0].sAfterModify) {
            window['$']("#addDendModal").modal('show');
          } else {
            //不是自动续约则不打开添加到期日modal
            // _.forEach(checkProduct, ite => {
            //   nFundNoList.push(ite.nFundNo);
            //   nAuditNoList.push(ite.nAuditNo);
            //   sStatusList.push(ite.sStatus);
            // })
            if (checkProduct[0].sStatus == '2') {
              window['swal']("注意", "该记录已经审核通过,请勿重复审核操作!", "warning");
            } else {
              window["swal"]({
                title: "注意",
                text: "是否确定审核通过",
                type: "warning",
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                showCancelButton: true,
                closeOnConfirm: false,
                closeOnCancel: true,
                showLoaderOnConfirm: true
              },
                function (isConfirm) {
                  if (isConfirm) {
                    let putBody: any = {
                      "nFundNo": checkProduct[0].nFundNo,
                      "sType": checkProduct[0].sType,
                      "auditStatus": "2",
                      "dExpire": that.dEnd,
                      "nExaminNo": checkProduct[0].nExaminNo
                    }
                    that.otmCheckService.checkPass(putBody).subscribe(data => {
                      if (data) {
                        window['swal']("成功", "已审核!", "success");
                        that.getCheckList();
                      }
                    })
                  }
                })
            }
          }
        }
      })
    }
    // 勾选多个
    if (checkProduct.length > 1) {
      // _.forEach(checkProduct, ite => {
      //   nFundNoList.push(ite.nFundNo);
      //   nAuditNoList.push(ite.nAuditNo);
      //   sStatusList.push(ite.sStatus);
      //   sTypeList.push(ite.sType);
      // })
      // if (_.includes(sStatusList, '2')) {
      //   window['swal']("注意", "勾选的记录中存在已经审核通过的记录,请勿重复审核操作!", "warning");
      // } else {
      //   if (_.includes(sTypeList, '2')) {
      //     window['swal']("注意", "续约只能单笔审核，请重新选择!", "warning")
      //   } else {
      //     window["swal"]({
      //       title: "注意",
      //       text: "是否确定审核通过",
      //       type: "warning",
      //       confirmButtonText: "确认",
      //       cancelButtonText: "取消",
      //       showCancelButton: true,
      //       closeOnConfirm: false,
      //       closeOnCancel: true,
      //       showLoaderOnConfirm: true
      //     },
      //       function (isConfirm) {
      //         if (isConfirm) {
      //           that.otmCheckService.checkPass(nFundNoList, nAuditNoList).subscribe(data => {
      //             if (data) {
      //               window['swal']("成功", "已审核!", "success");
      //               that.getCheckList();
      //             }
      //           })
      //         }
      //       })
      //   }
      // }
      window['swal']("注意", "只能单笔审核，请重新选择!", "warning")
    }
  }
  //  审核不通过
  checkNotPass() {
    let that = this;
    let checkProduct = [];
    let nFundNoList = [];
    let nAuditNoList = [];
    let sStatusList = [];
    let sTypeList = [];
    _.forEach(this.otmCheckList, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    // 无勾选
    if (checkProduct.length < 1) {
      window['swal']("注意", "请选择修改记录后再进行审核操作!", "warning")
    }
    // 勾选一个
    if (checkProduct.length == 1) {
      // _.forEach(checkProduct, ite => {
      //   nFundNoList.push(ite.nFundNo);
      //   nAuditNoList.push(ite.nAuditNo);
      //   sStatusList.push(ite.sStatus);
      // })
      if (checkProduct[0].sStatus == '2') {
        window['swal']("注意", "该记录已经审核通过,请勿重复审核操作!", "warning");
      } else {
        window["swal"]({
          title: "注意",
          text: "是否确定审核不通过",
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          showCancelButton: true,
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
          function (isConfirm) {
            if (isConfirm) {
              let putBody: any = {
                "nFundNo": checkProduct[0].nFundNo,
                "sType": checkProduct[0].sType,
                "auditStatus": "3",
                "dExpire": "",
                "nExaminNo": checkProduct[0].nExaminNo
              }
              that.otmCheckService.checkNotPass(putBody).subscribe(data => {
                if (data) {
                  window['swal']("成功", "已审核!", "success");
                  that.getCheckList();
                }
              })
            }
          })
      }
    }
    // 勾选多个
    if (checkProduct.length > 1) {
      // _.forEach(checkProduct, ite => {
      //   nFundNoList.push(ite.nFundNo);
      //   nAuditNoList.push(ite.nAuditNo);
      //   sStatusList.push(ite.sStatus);
      //   sTypeList.push(ite.sType);
      // })
      // if (_.includes(sStatusList, '2')) {
      //   window['swal']("注意", "勾选的记录中存在已经审核通过的记录,请勿重复审核操作!", "warning");
      // } else {
      //   if (_.includes(sTypeList, '2')) {
      //     window['swal']("注意", "续约只能单笔审核，请重新选择!", "warning")
      //   } else {
      //     window["swal"]({
      //       title: "注意",
      //       text: "是否确定审核不通过",
      //       type: "warning",
      //       confirmButtonText: "确认",
      //       cancelButtonText: "取消",
      //       showCancelButton: true,
      //       closeOnConfirm: false,
      //       closeOnCancel: true,
      //       showLoaderOnConfirm: true
      //     },
      //       function (isConfirm) {
      //         if (isConfirm) {
      //           that.otmCheckService.checkNotPass(nFundNoList, nAuditNoList).subscribe(data => {
      //             if (data) {
      //               window['swal']("成功", "已审核!", "success");
      //               that.getCheckList();
      //             }
      //           })
      //         }
      //       })
      //   }
      // }
      window['swal']("注意", "只能单笔审核，请重新选择!", "warning")
    }
  }
  // 打开 修改审核 modal
  showCheckModal(item) {
    window['$']("#checkModal").modal('show');
    // 判断组件是否已创建，如果创建先注销
    if (this.checkModalComponent && this.checkModalComponent.instance) {
      this.checkModalComponent.destroy();
    }

    // 动态创建组件的实例
    const checkModalComponent = this.resolver.resolveComponentFactory(OnetomanyCheckModalComponent);
    this.checkModalComponent = this.checkModal.createComponent(checkModalComponent);

    this.checkModalComponent.instance.onetomanyCheckDetailGetBody.nExaminNo = item.nExaminNo;
    this.checkModalComponent.instance.sFundType = item.sFundTypeName;
    this.checkModalComponent.instance.sTypeName = item.sTypeName;
  }
  //添加到期日
  addDend() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.otmCheckList, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })

    if (this.dEnd) {
      window["swal"]({
        title: "注意",
        text: "是否确定审核",
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        showCancelButton: true,
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
        function (isConfirm) {
          if (isConfirm) {
            let putBody: any = {
              "nFundNo": checkProduct[0].nFundNo,
              "sType": checkProduct[0].sType,
              "auditStatus": "2",
              "dExpire": that.dEnd,
              "nExaminNo": checkProduct[0].nExaminNo
            }
            that.otmCheckService.checkPass(putBody).subscribe(data => {
              if (data) {
                window['swal']("成功", "已审核!", "success");
                that.getCheckList();
                window['$']("#addDendModal").modal('hide');
              }
            })
          }
        })
    } else {
      window['swal']("警告", "请填写新的到期日", "warning");
    }

  }
  //修改审核明细表数据查询
  getCheckDetailList(item) {
    this.otmCheckService.getCheckDetailList({
      pageIndex: "1",
      pageSize: "10",
      sFundType: "2",
      nExaminNo: item
    }).subscribe(data => {
      if (data) {

        return data.list[0]
      }
    })
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.otmCheckList, [colName], ["asc"]);
    if (JSON.stringify(this.otmCheckList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.otmCheckList, [colName], ["desc"]);
    }
    this.otmCheckList = listDataAsc;
  }
}
